package com.xjtu.platform.demander.submit;


import com.xjtu.platform.common.CommonService;
import com.xjtu.platform.common.CurrentUser;
import com.xjtu.platform.common.Result;
import com.xjtu.platform.common.TokenUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/demander/submit")
public class submitAPI {

    @Resource
    private SubmitService submitService;

    @Resource
    private CommonService commonService;

    @PostMapping("/insert")
    public Result submit(@RequestHeader("Token")String token, @RequestBody submitDto dto){
        CurrentUser user = TokenUtils.getUserInfo(token, commonService);
        Integer numb = submitService.countSubmit(user);
        numb++;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date =new Date();
        String s = String.valueOf(numb);
        dto.setRequest_id(user.getUserId()+formatter.format(date)+s);
        dto.setUser_id(user.getUserId());
        dto.setStage(0);
        dto.setCreate_time(date);
        submitService.setSubmit(dto);
        return Result.success();
    }

    @GetMapping("/list")
    public Result submitList(@RequestHeader("Token")String token){
        CurrentUser user = TokenUtils.getUserInfo(token, commonService);
        List<submitDto> submitDtoList = submitService.getSubmitList(user);
        return Result.success(submitDtoList);
    }

    @GetMapping("/search")
    public Result searchByRequestId(@RequestBody submitDto dto){
        submitDto dto1 = submitService.searchByRequestId(dto.getRequest_id());
        return Result.success(dto1);
    }

    @PostMapping("/delete/{request_id}")
    public Result deleteSubmit(@PathVariable String request_id){
        submitDto dto =new submitDto();
        dto.setRequest_id(request_id);
        submitService.deleteSubmit(dto);
        return Result.success();
    }


    @PostMapping("/pic")
    public Result uploadQues(@RequestParam String path,@RequestBody MultipartFile[] files) throws IOException {
        System.out.println("需求数据文件路径为"+path);
        File dir = new File(CurrentUser.DEMO_DIR+"/"+path);
        System.out.println("长度"+files.length);
        if(!dir.exists()){
            dir.mkdirs();
            System.out.println("已为此需求创建创建文件夹");
        }
        String name = String.valueOf(UUID.randomUUID());
        if(files==null||files.length<1){
            return Result.fail(400,"文件为空！");
        }else{
            InputStream in = null;
            FileOutputStream out= null;
            try{
                for(int i = 0;i<files.length;i++){
                    in = files[i].getInputStream();
                    String submittedFilename = files[i].getOriginalFilename();
                    String nam = String.valueOf(UUID.randomUUID());
                    String suffix = submittedFilename.substring(submittedFilename.lastIndexOf("/"));
                    String filename = suffix;
                    suffix = filename.replace('.','-');
                    System.out.println("存入  "+filename+"  图片");
                    out = new FileOutputStream(CurrentUser.DEMO_DIR+"/"+path+filename);
                    Integer count=2;
                    submitService.insertQues(path,suffix,nam,count);
                    byte[] b =new byte[10240];
                    int len = -1;
                    try{
                        while((len = in.read(b))!=-1){
                            out.write(b,0,len);
                        }
                        out.flush();
                        out.close();
                        in.close();
                    }catch (Exception e){
                        e.printStackTrace();
                        out.flush();
                        out.close();
                        in.close();
                        return  Result.fail(400,"存入某张图片失败！");
                    }
                }
                Integer i = submitService.getStage(path);
                submitService.addStage(path,i);
                return Result.success("存入成功");
            }catch (Exception ec){
                ec.printStackTrace();
                return  Result.fail(400,"存入错误！");
            }
        }

    }

}
